package com.smartplatform.event.listener;

import com.smartplatform.event.DeviceLogEvent;
import com.smartplatform.mapper.SysDeviceLogMapper;
import com.smartplatform.pojo.SysDeviceLog;
import com.smartplatform.utils.RequestUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @Author 咕唧
 * @Date 2022/6/9 20:14
 * @Version 1.0
 */
@Component
public class DeviceLogListener {
    private ThreadPoolExecutor threadPoolExecutor;

    private SysDeviceLogMapper sysDeviceLogMapper;

    @Autowired
    public void setSysDeviceLogMapper(SysDeviceLogMapper sysDeviceLogMapper) {
        this.sysDeviceLogMapper = sysDeviceLogMapper;
    }

    @Autowired
    public void setThreadPoolExecutor(ThreadPoolExecutor threadPoolExecutor) {
        this.threadPoolExecutor = threadPoolExecutor;
    }

    @EventListener
    public void onEvent(DeviceLogEvent event){
        System.err.println("设备日志开启记录"+event);
        //获取request
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        //在request中获取ip地址
        CompletableFuture.runAsync(()->{
            String ip = RequestUtil.getRemoteHost(request);
            String locationByIp = RequestUtil.getLocationByIp(ip);
            SysDeviceLog sysDeviceLog=new SysDeviceLog();
            //设置设备id
            sysDeviceLog.setDeviceId(event.getDeviceId());
            //设置ip
            sysDeviceLog.setConnectIp(ip);
            //设置控制时间
            sysDeviceLog.setUpdateTime(new Date());
            //设置更新类型
            sysDeviceLog.setUpdateType(Long.valueOf(event.getType()));
            //设置ip所在地区
            sysDeviceLog.setConnectLocation(locationByIp);
            //添加到数据库
            sysDeviceLogMapper.insertAll(sysDeviceLog);
        },threadPoolExecutor);
    }
}
